import { ElMessage } from "element-plus";
import { chatStore } from "../../store/chatStore";
import { userStore } from "../../store/userStore";
import { MsgType, type GroupChat, type PrivateChat } from "../../types/types";
import { targetChatGroup } from "../socketPageService";
import { friendStore } from "../../store/friendStore";


// 定义一个消息枚举类型
enum MessageType {
    GROUP_JOINED = "GROUP_JOINED",
    UNIDIRECTIONAL = "unidirectional",
    RECEPT = "receipt",
    GROUP_CHAT_MESSAGE = "GROUP_CHAT-MESSAGE",
    GROUP_MESSAGE_ACK = "group-message-ack",
    PRIVATE_FILE_METADATA = "private-file-metadata",
    PRIVATE_FILE_ACK = "private-file-ack",
    GROUP_FILE_METADATA = "group-file-metadata",
    GROUP_FILE_ACK = "group-file-ack",
    GROUP_CREATED = "SNOW-CREATE_GROUP",
    GROUP_QUIT_RECEIPT = "group_quit-receipt",
    INVITATION_JOIN_GROUP = "invation-join-group",
    INVITE_RECEIPT = "invite-receipt",
    ACCEPT_FRIEND_NOTIFICATION = "accept-friend-notification",
    ADD_FRIEND_REQUEST = "add_friend_request"
}


export const handleMessage = (type: string, data: any): void => {
    const handler = messageHandlers[type] || defaultHandler;
    handler(data);
}

// 定义消息处理函数类型
type MessageHandler = (data?: any) => void;


// 首次加入群聊获取群成员信息
const handleGroupJoined: MessageHandler = (data: any) => {
    let groupId = data.groupId;
    const membersList = data.members;
    chatStore().setGroupMembers(groupId, membersList);
}
// 私聊信息（好友接收）
const handleUnidirectionalMessage: MessageHandler = (data: any) => {
    // 统一由 chatStore 保存，内部再区分好友/群聊
    chatStore().addPrivateMessage({
        id: data.messageId,
        chatId: data.chatId,             // 好友会话 id
        from: data.fromUserId,
        to: userStore().userInfo.uu_id,      // 当前登录人
        message: data.message,
        timeStamp: data.timestamp,
        status: 'received',                   // 已收到
        avatar: data.avatar,
        type: MsgType.TEXT
    });
}
// 私聊回执信息（发送者接收）
const handleReceipt: MessageHandler = (data: any) => {
    chatStore().addPrivateMessage({
        id: data.messageId,
        chatId: data.chatId,  // 自己的 id 作为 chatId 的一部分
        from: userStore().userInfo.uu_id,
        to: data.targetUserId,               // 接收方
        message: data.message,                         // 回执里通常不需要再带正文
        timeStamp: data.timestamp,
        status: data.status,                       // 标记“已发送”
        avatar: userStore().userInfo.avatar,
        type: MsgType.TEXT
    });
}
// 群聊信息（群友接收）
const handleMultiDirectionalMessage: MessageHandler = (data: any) => {
    chatStore().addGroupMessage({
        id: data.messageId || crypto.randomUUID(), // 后端最好给 messageId
        groupId: data.groupId,
        from: data.from,
        message: data.content,
        timeStamp: data.timestamp,
        userNickName: data.userNickName,
        userNickAvatar: data.userNickAvatar,
        type: MsgType.TEXT
    });
}
// 群聊回执信息（发送者接收）
const handleGroupMessageAck: MessageHandler = (data: any) => {
    chatStore().addGroupMessage({
        id: data.messageId || crypto.randomUUID(),
        groupId: data.groupId,
        from: data.from,
        message: data.message,
        timeStamp: data.timestamp,
        userNickName: data.userNickName,
        userNickAvatar: data.userNickAvatar,
        status: 'sent',
        avatar: data.avatar,
        type: MsgType.TEXT
    });
}
// 私聊文件元数据信息（私聊好友接收）
const handlePrivateFileMetadata: MessageHandler = (data: any) => {
    chatStore().addPrivateMessage({
        id: data.messageId || crypto.randomUUID(),
        chatId: data.chatId,                 // 会话 id
        from: data.senderId,
        to: userStore().userInfo.uu_id,
        message: JSON.stringify({
            fileKey: data.fileKey,
            fileName: data.fileName,
            fileSize: data.fileSize,
            fileURL: data.fileUrl, // ⭐后端给的下载地址
            mimeType: data.mimeType,
            isImage: data.mimeType?.startsWith('image/')
        }),
        timeStamp: data.timestamp,
        status: 'received',
        avatar: data.userNickAvatar, // 让头像组件自己取好友头像,
        type: MsgType.FILE
    })
}
// 私聊文件元数据回执信息（发送者接收）
const handlePrivateFileMetadataAck: MessageHandler = (data: any) => {
    chatStore().addPrivateMessage({
        id: data.messageId || crypto.randomUUID(),
        chatId: data.from + "-" + data.to,               // 会话 id
        from: userStore().userInfo.uu_id,
        to: data.to,
        message: JSON.stringify({
            fileKey: data.fileKey,
            fileName: data.fileName,
            fileSize: data.fileSize,
            fileURL: data.fileUrl,
            mimeType: data.mimeType,
            isImage: data.mimeType?.startsWith('image/')
        }),
        timeStamp: data.timestamp,
        status: 'sent',
        userNickName: data.userNickName,
        userNickAvatar: data.userNickAvatar,
        avatar: userStore().userInfo.avatar,
        type: MsgType.FILE
    });
}
// 群聊文件元数据（群友接收）
const handleGroupFileMetadata: MessageHandler = (data: any) => {
    chatStore().addGroupMessage({
        id: data.messageId || crypto.randomUUID(),
        groupId: data.to,
        from: data.from,
        message: JSON.stringify({
            fileKey: data.fileKey,
            fileName: data.fileName,
            fileSize: data.fileSize,
            fileURL: data.fileUrl,
            mimeType: data.mimeType,
            isImage: data.mimeType?.startsWith('image/')
        }),
        timeStamp: data.timestamp,
        status: 'received',
        userNickName: data.userNickName,
        userNickAvatar: data.userNickAvatar,
        avatar: data.avatar,
        type: MsgType.FILE
    });
}
// 群聊元数据回执信息（发送者接收）
const handleGroupFileMetadataAck: MessageHandler = (data: any) => {
    chatStore().addGroupMessage({
        id: data.messageId || crypto.randomUUID(),
        groupId: data.to,
        from: data.senderId,            // 其实from就是sender       to就是toCHhatId
        message: JSON.stringify({
            fileKey: data.fileKey,
            fileName: data.fileName,
            fileSize: data.fileSize,
            fileURL: data.fileUrl,
            mimeType: data.mimeType,
            isImage: data.mimeType?.startsWith('image/')
        }),
        timeStamp: data.timestamp,
        userNickName: data.userNickName,
        userNickAvatar: data.userNickAvatar,
        status: 'received',
        avatar: userStore().userInfo.avatar,
        type: MsgType.FILE
    });
}
// 创建群聊的事件
const handleCreateGroup: MessageHandler = (data: any) => {
    if (data.message && data.message.trim() != '') {
        ElMessage.error(data.message);
    } else {
        // 解析消息
        const groupInfo = JSON.parse(data.groupInfo);
        // 扩展群聊信息对象
        const groupObject: GroupChat = {
            group_id: groupInfo.groupId, group_name: groupInfo.groupName,
            group_type: groupInfo.groupType, group_leader: groupInfo.groupLeader,
            group_key: groupInfo.groupKey, groupAvatar: groupInfo.groupAvatar,
            type: "group-chat"
        }
        // 向当前用户群聊列表添加群聊信息
        friendStore().addToMergeList(groupObject);
    }
}
// 群友退出群聊的信息
const handleGroupQuitReceipt: MessageHandler = (data: any) => {
    ElMessage.success(`${data.message}`);
    // 在这里执行删除群聊信息的操作（为了确保数据的安全，不会误删）
    if (data.status === 'success') {
        chatStore().clearGroupInfoByGroupId(data.groupId, "quit-and-clear");
        chatStore().quitGroup(targetChatGroup.group_id);
        chatStore().removeMembers(data.groupId, userStore().userInfo.uu_id);
    }
}
// 邀请好友加入群聊的信息（被邀请者接收）
const handleInviteJoginGroup: MessageHandler = (data: any) => {
    chatStore().addGroupMessage({
        id: data.chatId || data.messageKey || crypto.randomUUID(),
        groupId: data.groupId,
        from: data.from,
        message: data.message,
        timeStamp: data.timeStamp,
        // userNickName: userStore().userInfo.username,
        // userNickAvatar: userStore().userInfo.avatar,
        type: MsgType.GroupInvation,
        invationList: data.invation
    })
    if (userStore().userInfo) {
        const userStoreInstance = userStore().userInfo;
        const receiverInfo = {
            key: userStoreInstance.uu_id,
            label: userStoreInstance.username,
            avatar: userStoreInstance.avatar
        };
        data.invation.push(receiverInfo);       // 也就是当前用户的key、label、avatar信息
    }
    chatStore().storageGroupInfo(data.groupInfo);
    chatStore().addGroupMembers(data.groupId, data.invation);
}
// 邀请好友加入群聊的回执信息（邀请者接收）
const handleInviteReceipt: MessageHandler = (data: any) => {
    ElMessage.success(data.message);
    chatStore().addGroupMessage({
        id: data.chatId || data.messageKey || crypto.randomUUID(),
        groupId: targetChatGroup.group_id,
        from: userStore().userInfo.uu_id,
        message: data.message,
        timeStamp: data.timeStamp,
        userNickName: userStore().userInfo.username,
        userNickAvatar: userStore().userInfo.avatar,
        type: MsgType.GroupInvation,
        invationList: data.invatin
    })
    chatStore().addGroupMembers(targetChatGroup.group_id, data.invationList)        // 在这里可以加进来（也就是说在拉取的时候可以正常加载到pinia store中）这里就不用管了，后期优化就好
}
// 处理添加好友请求信息
const handleAddFriendRequest: MessageHandler = (data: any) => {
    if (data.status === 'success') {
        // 解析JSON字符串
        const requestInfo = data.messageContent;
        friendStore().setFriendRequestList(requestInfo);
    }
}
// 处理同意好友信息（接收信息、回执信息一起执行）
const handleAcceptFriend: MessageHandler = (data: any) => {    // 获取sub-type
    const subType = data.subType;
    if ((subType === 'receipt' || subType === 'respond') && data.status === 'accepted') {
        // 构建好友对象
        const friendObject: PrivateChat = {
            friendId: data.friendDetails.uuId,
            friendName: data.friendDetails.friendName,
            friendAvatar: data.friendDetails.friendAvatar,
            type: "private-chat"
        }
        ElMessage.success(data.messageContent);
        if (data.requestId!.trim() !== '') {
            friendStore().removeFriendRequestById(data.requestId);
        }
        friendStore().addToMergeList(friendObject);
    } else if (subType === 'error') {
        ElMessage.error(`${data.errorInfoDetails}`);
    }
}

// 创建处理函数映射
const messageHandlers: { [key: string]: MessageHandler } = {
    [MessageType.GROUP_JOINED]: handleGroupJoined,
    [MessageType.UNIDIRECTIONAL]: handleUnidirectionalMessage,
    [MessageType.RECEPT]: handleReceipt,
    [MessageType.GROUP_CHAT_MESSAGE]: handleMultiDirectionalMessage,
    [MessageType.GROUP_MESSAGE_ACK]: handleGroupMessageAck,
    [MessageType.PRIVATE_FILE_METADATA]: handlePrivateFileMetadata,
    [MessageType.PRIVATE_FILE_ACK]: handlePrivateFileMetadataAck,
    [MessageType.GROUP_FILE_METADATA]: handleGroupFileMetadata,
    [MessageType.GROUP_FILE_ACK]: handleGroupFileMetadataAck,
    [MessageType.GROUP_QUIT_RECEIPT]: handleGroupQuitReceipt,
    [MessageType.INVITATION_JOIN_GROUP]: handleInviteJoginGroup,
    [MessageType.INVITE_RECEIPT]: handleInviteReceipt,
    [MessageType.ACCEPT_FRIEND_NOTIFICATION]: handleAcceptFriend,
    [MessageType.ADD_FRIEND_REQUEST]: handleAddFriendRequest,
    [MessageType.GROUP_CREATED]: handleCreateGroup
}

// 默认处理事件
const defaultHandler: MessageHandler = () => {
    ElMessage.error("未知来信！哈哈哈");
}